//
//  AddressManagerController.m
//  EasyToTesco2.0
//
//  Created by 杨森 on 16/6/21.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "AddressManagerController.h"
#import "getAddressCell.h"

#import "CreatAddressController.h"
#import "EditAddressController.h"
#import "AddressModel.h"

@interface AddressManagerController ()<UITableViewDelegate,UITableViewDataSource>
{
    MBProgressHUD *progressHUD;
    UIImageView *noDrawImage;
    NSInteger *section;
}

@property(nonatomic,strong)UITableView *addressTableView;

@property(nonatomic,strong)NSMutableArray *addressArray;

@end

@implementation AddressManagerController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    
    NSLog(@"%@",self.productArray);
    //获取用户地址列表
    [self getUserAddressRequestData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"管理收货地址";

    [self addTableViewUI];
   
}


- (void)addTableViewUI
{
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    UITableView *addressTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64-40) style:UITableViewStyleGrouped];
    [self.view addSubview:addressTableView];
    self.addressTableView = addressTableView;
    addressTableView.rowHeight = 110;
    addressTableView.delegate = self;
    addressTableView.dataSource = self;
    
    
    //添加新地址
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:btn];
    btn.frame = CGRectMake(0,HEIGHT-40-64, WIDTH, 40);
    [btn setBackgroundColor:DEFAULT_COLOR];
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    [btn setTitle:@"+ 添加新地址" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(didCreatAddressClick) forControlEvents:UIControlEventTouchUpInside];
    
}

#pragma mark >>>>>>>> 添加新地址
- (void)didCreatAddressClick
{
    CreatAddressController *CreatVC = [[CreatAddressController alloc] init];
    [self.navigationController pushForm:self.navigationController pushToAndHidden:CreatVC];
}


#pragma mark >>>>>>>> 按钮点击
//默认按钮
- (void)defaultBtnClick:(UIButton *)button
{
    //菊花加载
    progressHUD = [MBProgressHUD loadingInformationToView];
    [self.view addSubview:progressHUD];
    
    [self setupDefaultUserAddressRequestData:button];
}

//编辑
- (void)editBtnClick:(UIButton *)button
{
    EditAddressController *editVC = [[EditAddressController alloc] init];
    AddressModel *addressModel = self.addressArray[button.tag];
    editVC.addressModel = addressModel;
    [self.navigationController pushForm:self.navigationController pushToAndHidden:editVC];
}

//删除
- (void)deleteBtnClick:(UIButton *)button
{
    //弹框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确定删除收货地址?" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *okay = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //菊花加载
        progressHUD = [MBProgressHUD loadingInformationToView];
        [self.view addSubview:progressHUD];
        
        //删除请求
        [self deleteUserAddressRequestData:button];
    }];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消");
    }];
    
    [alert addAction:okay];
    [alert addAction:cancle];
    
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark >>>>>>>>>>>>获取用户地址列表
- (void)getUserAddressRequestData
{
    
    
    [self.addressArray removeAllObjects];
    [noDrawImage removeFromSuperview];
    
    NSDictionary *params = @{@"username":[NSString stringWithFormat:@"%@", USERNAME]};
    
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/User/addressList" completeBlock:^(id object) {
        
        if (JudgeBackDataCode) {
            NSArray *tempArr = [object objectForKey:@"data"];
            for (NSDictionary *dict in tempArr) {
                 AddressModel *addressModel = [[AddressModel alloc] initWithDictionary:dict error:nil];
                if (addressModel) {
                    [self.addressArray addObject:addressModel];
//                    NSLog(@"%@",addressModel);
                }
            }
        }else{
            //暂无地址(图)
            noDrawImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"noAddress"]];
            [self.view addSubview:noDrawImage];
            
            [noDrawImage mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(self.view.mas_centerX);
                make.centerY.equalTo(self.view.mas_centerY).offset(-HEIGHT/10);
                make.width.mas_equalTo(WIDTH/2);
                make.height.mas_equalTo(HEIGHT/4);
            }];
            
        }
        [self.addressTableView reloadData];
        [progressHUD hide:YES];
    }];
}


#pragma mark >>>>>>>>>>>>删除用户地址
- (void)deleteUserAddressRequestData:(UIButton *)button
{
    AddressModel *addressModel = self.addressArray[button.tag];
    
    NSDictionary *params = @{@"address_id":[NSString stringWithFormat:@"%d",addressModel.re_id],
                             @"username":[NSString stringWithFormat:@"%@",USERNAME]};
    NSLog(@"%@",params);
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/User/deleteAddress" completeBlock:^(id object) {
        
        NSLog(@"%@",object);
        if (JudgeBackDataCode) {
            [self getUserAddressRequestData];
        }
    }];
}

#pragma mark >>>>>>>>>>>>设置默认用户地址
- (void)setupDefaultUserAddressRequestData:(UIButton *)button
{
    AddressModel *addressModel = self.addressArray[button.tag];
    
    NSDictionary *params = @{@"address_id":[NSString stringWithFormat:@"%d",addressModel.re_id],@"username":[NSString stringWithFormat:@"%@",USERNAME]};
    
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/User/setDefaultAddress" completeBlock:^(id object) {
        
//        NSLog(@"%@",object);
        if (JudgeBackDataCode) {
            [self getUserAddressRequestData];

        }
    }];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.addressArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifier = @"getAddressCell";
    
    getAddressCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (cell==nil) {
        cell= [[[NSBundle mainBundle] loadNibNamed:@"getAddressCell" owner:nil options:nil] lastObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    
    AddressModel *addressModel = self.addressArray[indexPath.section];
    //姓名
    cell.nameLabel.text = addressModel.name;
    //电话
    cell.phoneLabel.text = addressModel.phone;
    //地址
    cell.addressLabel.text = [NSString stringWithFormat:@"%@%@%@",addressModel.city,addressModel.county,addressModel.address];
    
    [cell.defaultBtn setTitleColor:DEFAULT_COLOR forState:UIControlStateSelected];
    [cell.defaultBtn setImage:[UIImage imageNamed:@"icon_mr_h"] forState:UIControlStateSelected];
    [cell.defaultBtn setTitle:@"默认地址" forState:UIControlStateSelected];
    
    [cell.defaultBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [cell.defaultBtn setImage:[UIImage imageNamed:@"icon_mr_n"] forState:UIControlStateNormal];
//    默认
    if (addressModel.zt == 1) {
        cell.defaultBtn.selected = YES;
        
    }else{
        cell.defaultBtn.selected = NO;
        
    }
    
    [cell.defaultBtn setTitle:@"设为默认" forState:UIControlStateNormal];
    [cell.defaultBtn addTarget:self action:@selector(defaultBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    cell.defaultBtn.tag = indexPath.section;
    
    //编辑
    
    [cell.editBtn addTarget:self action:@selector(editBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    cell.editBtn.tag = indexPath.section;
    
    //删除
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    cell.deleteBtn.tag = indexPath.section;
    
    
    return cell;
}

#pragma mark>>>>>>>>> 代理
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ([self.delegate respondsToSelector:@selector(addViewController:addUser:andProductArray:)]) {
//        [self.delegate addViewController:self addUser:self.addressArray[indexPath.section]];
        [self.delegate addViewController:self addUser:self.addressArray[indexPath.section] andProductArray:self.productArray];
    }
    
    [self.navigationController popViewControllerAnimated:YES];

}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

- (NSMutableArray *)addressArray {
    if (!_addressArray) {
        _addressArray = [NSMutableArray array];
    }
    return _addressArray;
}

- (NSMutableArray *)productArray {
    if (!_productArray) {
        _productArray = [NSMutableArray array];
    }
    return _productArray;
}

@end
